package cn.hejiang.mamis.core.util;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import cn.hejiang.mamis.core.dto.OptionDTO;
import cn.hejiang.mamis.core.entity.BaseEntity;
import cn.hejiang.mamis.core.entity.TreeEntity;
import cn.hutool.core.util.StrUtil;

public class EntityUtil {

	public static <T extends TreeEntity<? super T>> List<T> plainToTree(Collection<T> plain) {
		return getSiblings(null, plain);
	}

	private static <T extends TreeEntity<? super T>> List<T> getSiblings(String pid, Collection<T> plain) {
		List<T> list = plain.stream().filter(i -> StrUtil.equals(i.getPid(), pid)).collect(Collectors.toList());

		list.forEach(i -> {
			List<T> children = getSiblings(i.getId(), plain);
			if (children != null && children.size() > 0) {
				i.setChildren(children);
			}
		});

		return list;
	}

	public static <T extends TreeEntity<T>> List<OptionDTO> toOptionTree(Collection<? extends T> tree) {
		return tree.stream().map(i -> {
			OptionDTO o = new OptionDTO();

			o.setValue(i.getId());
			o.setLabel(i.getName());

			Collection<? extends T> children = i.getChildren();
			if (children != null && children.size() > 0) {
				o.setChildren(toOptionTree(children));
			}

			return o;
		}).collect(Collectors.toList());
	}

	public static <T extends TreeEntity<T>> List<String> toOptionPathList(Collection<T> tree) {
		return toOptionPathStream(null, tree).collect(Collectors.toList());
	}

	private static <T extends TreeEntity<T>> Stream<String> toOptionPathStream(String prefix,
			Collection<? extends T> tree) {
		return tree.stream().flatMap(i -> {
			StringBuilder builder = new StringBuilder();

			if (StrUtil.isNotBlank(prefix)) {
				builder.append(prefix).append("/");
			}

			builder.append(i.getId());

			Collection<? extends T> children = i.getChildren();
			if (children != null && children.size() > 0) {
				return toOptionPathStream(builder.toString(), children);
			} else {
				return Arrays.asList(builder.toString()).stream();
			}
		});
	}

	public static <T extends BaseEntity> List<OptionDTO> toOptionList(Collection<T> list) {
		return list.stream().map(i -> {
			OptionDTO o = new OptionDTO();

			o.setValue(i.getId());
			o.setLabel(i.getName());

			return o;
		}).collect(Collectors.toList());
	}

}
